package com.util;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IPUtil {
	
	public static String getIp() {
		byte[] b = null;
		Enumeration<NetworkInterface> allNetInterfaces = null;
		try {
			b = InetAddress.getLocalHost().getAddress();
			allNetInterfaces = NetworkInterface.getNetworkInterfaces();
		} catch (Exception e1) {
			e1.printStackTrace();
		}	
		InetAddress ip = null;
		NetworkInterface netInterface = null;
		while (allNetInterfaces.hasMoreElements()) {
			netInterface = (NetworkInterface) allNetInterfaces.nextElement();
			if (netInterface.getName().trim().equals("eth0")){
				Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					ip = (InetAddress) addresses.nextElement();
				}
				break;
			}
		}
		if (ip != null && ip instanceof Inet4Address) {
			b = ip.getAddress();
		}
		return getStrByByte(b);
	}
	
	private static String getStrByByte(byte[] b){
		String strIp="";
		for(byte bytes:b) { 
			if(bytes>=0)
				strIp+=bytes+"."; 
			else 
				strIp += 256+bytes+"."; 
		}  
		return strIp.substring(0, strIp.length()-1);
	}
}
